package com.wutongyu.mannyburger;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;

import java.util.Random;

public class UserInfoFragment extends Fragment {

    private static final String TAG = "UserInfoFragment";
    private static final String ARG_PHONE = "phone";
    
    // 头像资源ID数组
    private static final int[] AVATAR_RESOURCES = {

            R.drawable.avatar_custom_1,
            R.drawable.avatar_custom_2,
            R.drawable.avatar_custom_3,
            R.drawable.avatar_custom_4
    };
    
    private String phone;
    private UserDatabaseHelper userDbHelper;
    
    // UI组件
    private Toolbar toolbar;
    private ImageView imageViewAvatar;
    private ImageView imageViewEditAvatar;
    private EditText editTextUsername;
    private TextView textViewPhone;
    private RadioGroup radioGroupGender;
    private RadioButton radioButtonMale;
    private RadioButton radioButtonFemale;
    private EditText editTextAddress;
    private Button buttonSave;
    
    // 当前头像ID
    private int currentAvatarId;
    
    // 静态工厂方法，用于创建Fragment实例
    public static UserInfoFragment newInstance(String phone) {
        UserInfoFragment fragment = new UserInfoFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PHONE, phone);
        fragment.setArguments(args);
        return fragment;
    }
    
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            phone = getArguments().getString(ARG_PHONE);
        }
        
        userDbHelper = new UserDatabaseHelper(requireContext());
    }
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_user_info, container, false);
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        // 初始化UI组件
        initializeViews(view);
        
        // 设置工具栏导航返回
        setupToolbar();
        
        // 加载用户信息
        loadUserInfo();
        
        // 设置点击事件
        setupClickListeners();
    }
    
    private void initializeViews(View view) {
        toolbar = view.findViewById(R.id.toolbar);
        imageViewAvatar = view.findViewById(R.id.image_view_avatar);
        imageViewEditAvatar = view.findViewById(R.id.image_view_edit_avatar);
        editTextUsername = view.findViewById(R.id.edit_text_username);
        textViewPhone = view.findViewById(R.id.text_view_phone);
        radioGroupGender = view.findViewById(R.id.radio_group_gender);
        radioButtonMale = view.findViewById(R.id.radio_button_male);
        radioButtonFemale = view.findViewById(R.id.radio_button_female);
        editTextAddress = view.findViewById(R.id.edit_text_address);
        buttonSave = view.findViewById(R.id.button_save);
    }
    
    private void setupToolbar() {
        toolbar.setNavigationOnClickListener(v -> {
            // 返回上一页
            requireActivity().getSupportFragmentManager().popBackStack();
        });
    }
    
    private void loadUserInfo() {
        ContentValues userInfo = userDbHelper.getUserInfo(phone);
        
        if (userInfo != null) {
            // 设置手机号
            textViewPhone.setText(phone);
            
            // 设置用户名
            String username = userInfo.getAsString(UserDatabaseHelper.COLUMN_USERNAME);
            if (!TextUtils.isEmpty(username)) {
                editTextUsername.setText(username);
            }
            
            // 设置地址
            String address = userInfo.getAsString(UserDatabaseHelper.COLUMN_ADDRESS);
            if (!TextUtils.isEmpty(address)) {
                editTextAddress.setText(address);
            }
            
            // 设置性别
            String gender = userInfo.getAsString(UserDatabaseHelper.COLUMN_GENDER);
            if (!TextUtils.isEmpty(gender)) {
                if (gender.equals("女")) {
                    radioButtonFemale.setChecked(true);
                } else {
                    radioButtonMale.setChecked(true);
                }
            } else {
                // 默认为男性
                radioButtonMale.setChecked(true);
            }
            
            // 设置头像
            Integer avatarId = userInfo.getAsInteger(UserDatabaseHelper.COLUMN_AVATAR_ID);
            try {
                if (avatarId != null && avatarId > 0 && isResourceValid(avatarId)) {
                    currentAvatarId = avatarId;
                    imageViewAvatar.setImageResource(currentAvatarId);
                    Log.i(TAG, "正在使用头像资源ID: " + currentAvatarId);
                } else {
                    // 如果没有设置头像ID或头像资源无效，使用安全的默认头像
                    currentAvatarId = getSafeDefaultAvatarId();
                    imageViewAvatar.setImageResource(currentAvatarId);
                    Log.w(TAG, "用户头像ID无效或不存在，已设置安全默认头像: " + currentAvatarId);
                }
            } catch (Exception e) {
                // 处理头像加载异常
                Log.e(TAG, "设置用户头像时出错: " + e.getMessage(), e);
                try {
                    // 尝试使用备用系统头像
                    currentAvatarId = android.R.drawable.ic_menu_gallery;
                    imageViewAvatar.setImageResource(currentAvatarId);
                } catch (Exception fallbackEx) {
                    // 严重错误，无法设置任何头像，但不应导致应用崩溃
                    Log.e(TAG, "设置备用头像也失败，忽略头像显示", fallbackEx);
                }
            }
        } else {
            Log.e(TAG, "无法获取用户信息: " + phone);
            Toast.makeText(getContext(), "加载用户信息失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 检查资源ID是否有效
     */
    private boolean isResourceValid(int resourceId) {
        try {
            if (getResources() == null) {
                Log.w(TAG, "资源检查时资源对象为空");
                return false;
            }
            
            // 尝试获取资源名称，如果资源不存在会抛出异常
            getResources().getResourceName(resourceId);
            
            // 进一步确认是否为可绘制资源
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    getResources().getDrawable(resourceId, requireContext().getTheme());
                } else {
                    getResources().getDrawable(resourceId);
                }
                return true;
            } catch (Exception e) {
                Log.w(TAG, "资源ID " + resourceId + " 不是可绘制资源", e);
                return false;
            }
        } catch (Exception e) {
            Log.w(TAG, "资源ID无效: " + resourceId, e);
            return false;
        }
    }
    
    /**
     * 获取安全的默认头像ID
     */
    private int getSafeDefaultAvatarId() {
        // 自定义头像列表，按优先顺序排列
        int[] safeAvatars = {
            R.drawable.avatar_custom_1,
            R.drawable.avatar_custom_2,
            R.drawable.avatar_custom_3,
            R.drawable.avatar_custom_4
        };
        
        // 逐个尝试找到一个有效的头像资源
        for (int avatarId : safeAvatars) {
            if (isResourceValid(avatarId)) {
                return avatarId;
            }
        }
        
        // 如果所有自定义头像都无效，才使用系统图标作为最后备选
        try {
            return android.R.drawable.ic_menu_gallery;
        } catch (Exception e) {
            Log.e(TAG, "无法获取任何有效的头像资源", e);
            return 0; // 最终失败情况下返回0
        }
    }
    
    private void setupClickListeners() {
        // 头像点击事件
        imageViewAvatar.setOnClickListener(v -> showAvatarSelectionDialog());
        
        // 编辑头像按钮点击事件
        imageViewEditAvatar.setOnClickListener(v -> showAvatarSelectionDialog());
        
        // 保存按钮点击事件
        buttonSave.setOnClickListener(v -> saveUserInfo());
    }
    
    private void showAvatarSelectionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("选择头像");
        
        // 创建布局
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_avatar_selection, null);
        builder.setView(dialogView);
        
        // 获取GridLayout
        final ViewGroup gridLayout = dialogView.findViewById(R.id.grid_layout_avatars);
        
        // 创建对话框
        final AlertDialog dialog = builder.create();
        
        // 动态添加头像选项
        for (int i = 0; i < AVATAR_RESOURCES.length; i++) {
            final int avatarId = AVATAR_RESOURCES[i];
            
            try {
                // 检查头像资源是否有效
                if (!isResourceValid(avatarId)) {
                    Log.w(TAG, "跳过无效的头像资源ID: " + avatarId);
                    continue;
                }
                
                // 创建ImageView
                ImageView avatarImageView = new ImageView(requireContext());
                avatarImageView.setImageResource(avatarId);
                
                // 设置布局参数
                ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT, 
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                params.width = getResources().getDimensionPixelSize(R.dimen.avatar_dialog_size);
                params.height = getResources().getDimensionPixelSize(R.dimen.avatar_dialog_size);
                params.setMargins(8, 8, 8, 8);
                
                avatarImageView.setLayoutParams(params);
                
                // 设置点击事件
                avatarImageView.setOnClickListener(v -> {
                    try {
                        // 更新头像
                        currentAvatarId = avatarId;
                        imageViewAvatar.setImageResource(currentAvatarId);
                    } catch (Exception e) {
                        Log.e(TAG, "设置头像资源出错: " + e.getMessage(), e);
                        Toast.makeText(requireContext(), "设置头像失败", Toast.LENGTH_SHORT).show();
                    }
                    
                    // 关闭对话框
                    dialog.dismiss();
                });
                
                // 添加到GridLayout
                gridLayout.addView(avatarImageView);
            } catch (Exception e) {
                Log.e(TAG, "添加头像选项时出错: " + e.getMessage(), e);
                // 继续添加其他头像选项，不要因为一个出错就中断整个流程
            }
        }
        
        // 确保至少有一个有效头像选项
        if (gridLayout.getChildCount() == 0) {
            Log.w(TAG, "没有有效的头像选项可显示，添加默认系统图标");
            try {
                // 添加一个系统默认图标作为备选
                ImageView defaultImageView = new ImageView(requireContext());
                defaultImageView.setImageResource(android.R.drawable.ic_menu_gallery);
                
                ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT, 
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                params.width = getResources().getDimensionPixelSize(R.dimen.avatar_dialog_size);
                params.height = getResources().getDimensionPixelSize(R.dimen.avatar_dialog_size);
                params.setMargins(8, 8, 8, 8);
                
                defaultImageView.setLayoutParams(params);
                
                defaultImageView.setOnClickListener(v -> {
                    currentAvatarId = android.R.drawable.ic_menu_gallery;
                    imageViewAvatar.setImageResource(currentAvatarId);
                    dialog.dismiss();
                });
                
                gridLayout.addView(defaultImageView);
            } catch (Exception e) {
                Log.e(TAG, "添加默认头像选项也失败", e);
                // 严重错误处理
                Toast.makeText(requireContext(), "无法加载头像选项", Toast.LENGTH_SHORT).show();
                dialog.dismiss(); // 关闭对话框，避免显示空白选择界面
                return;
            }
        }
        
        dialog.show();
    }
    
    private void saveUserInfo() {
        // 获取输入的用户信息
        String username = editTextUsername.getText().toString().trim();
        String address = editTextAddress.getText().toString().trim();
        String gender = radioButtonMale.isChecked() ? "男" : "女";
        
        // 验证用户名
        if (TextUtils.isEmpty(username)) {
            editTextUsername.setError("用户名不能为空");
            return;
        }
        
        // 记录保存的头像ID
        Log.i(TAG, "保存用户信息，头像资源ID: " + currentAvatarId);
        
        // 保存用户信息
        boolean success = userDbHelper.updateUserFullInfo(phone, username, address, currentAvatarId, gender);
        
        if (success) {
            Toast.makeText(getContext(), "个人信息已更新", Toast.LENGTH_SHORT).show();
            
            // 返回上一页
            requireActivity().getSupportFragmentManager().popBackStack();
        } else {
            Toast.makeText(getContext(), "保存失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 关闭数据库连接
        if (userDbHelper != null) {
            userDbHelper.close();
        }
    }
} 